<?php
// +----------------------------------------------------------------------+
// | Author:  Evgeny Leontev <eleontev@gmail.com>                         |
// | Copyright (c) 2005 Evgeny Leontev                                    |
// +----------------------------------------------------------------------+
// | This source file is free software; you can redistribute it and/or    |
// | modify it under the terms of the GNU Lesser General Public           |
// | License as published by the Free Software Foundation; either         |
// | version 2.1 of the License, or (at your option) any later version.   |
// |                                                                      |
// | This source file is distributed in the hope that it will be useful,  |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of       |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    |
// | Lesser General Public License for more details.                      |
// +----------------------------------------------------------------------+

/**
 * Navigation is a class to generate navigation menu.
 *
 * @version 1.0
 * @since 01/15/2004
 * @author Evgeny Leontev 
 * @access public
 *
 * EXAMPLE
 * 
 *
 * CHANGELOG
 * 01/15/2004 - release
 */
 
class Navigation
{

	var $equal_type;		// PAGE or GET or CATALOG
	var $equal_value;	
	
	var $sub_equal_type;		// PAGE or GET or CATALOG
	var $sub_equal_value;	
	
	var $order = 0;
	var $max_order = 0;
	//var $orders = array();
	var $do_check_value = true;
	
	var $menu_name = 'default';
	var $menu_array = array();
	var $auxilary = array();
	var $template;
	var $template_type;
	var $default_value;
	var $custom_rule;
	var $ext = '.php';
	var $get_params = array();
	var $options = array('target'=>'_self', 'a_style'=>'',  'a_extra'=>'',
	                                        'td_style'=>'', 'td_extra'=>'');	
	
	
	function setMenuName($menu_name) {
		$this->menu_name = $menu_name;
	}
	

	// $type = PAGE or GET or CATALOG
	function setEqualAttrib($type, $value = false) {
		$this->equal_type = $type;
		$this->equal_value = $value;
	}

	
	function setOption($name, $value) {
		$this->options[$name] = $value;
	}
	
/*
	// $type = PAGE or GET or CATALOG
	function setSubEqualAttrib($type, $value = false) {
		$this->sub_equal_type = $type;
		$this->sub_equal_value = $value;
	}
*/
	
	
	// $type = PAGE or GET or CATALOG
	function setSubEqualAttrib($type, $value = false) {
		$this->sub_equal[] = array('type'=>$type, 'value'=>$value);
	}	
	

	function setDefault($value) {
		$this->default_value = $value;
	}
	
	// check value or not by _getCheckValue and insert it to auxilary array
	function setDoCheckValue($val) {
		$this->do_check_value = $val;
	}
	
	
	function setOrder($val) {
		$this->order = $val;
	}
	
	function countMenuItems($menu_name = false) {
		
		$num = 0;
		if($menu_name == 'all') {
			foreach($this->menu_array as $v) {
				$num += count($v); 
			}
		} elseif(!$menu_name) {
			$num = count($this->menu_array[$this->menu_name]);
		} else {
			$num = count($this->menu_array[$menu_name]);
		}
		
		return $num;
	}
	
	
	function reassignOrder(&$val) {
		if(isset($this->menu_array[$this->menu_name][$val])) {
			
			$num = count($this->menu_array[$this->menu_name]);
			
			for($i=$val,$j=0;$i<$num;$i++,$j++){
				$key = $num-$j-1;
				$this->menu_array[$this->menu_name][$key+1] = $this->menu_array[$this->menu_name][$key];
				unset($this->menu_array[$this->menu_name][$key]);
				
				if(isset($this->auxilary[$this->menu_name][$val])) {
					$this->auxilary[$this->menu_name][$key+1] = $this->auxilary[$this->menu_name][$key];
					unset($this->auxilary[$this->menu_name][$key]);	
				}
			}
		}
	}	
	
	
	function setMenuItem($menu_item, $menu_link, $options = array()) {
		
		$order = (isset($this->menu_array[$this->menu_name])) ? count($this->menu_array[$this->menu_name]) : 0;
		if($this->order) {
			$order = $this->order;
			$this->reassignOrder($order);
		}
	
		$this->menu_array[$this->menu_name][$order] = array('menu_item' => $menu_item, 'menu_link' => $menu_link);
		if($this->do_check_value) {
			$this->auxilary[$this->menu_name][$order] = $this->_getCheckValue($menu_link);
		}
		
		if($options) {
			foreach($options as $k => $v) {
				$this->menu_array[$this->menu_name][$order][$k] = $v;
			}
		}
		
		$this->order = 0;
	}
	
	
	function updateMenuItem($menu_item_code, $menu_item, $menu_link, $options = array()) {
		$key = array_search($menu_item_code, $this->auxilary[$this->menu_name]);
		if($key !== false) {
			$menu_item = ($menu_item != false) ?  $menu_item : $this->menu_array[$this->menu_name][$key]['menu_item'];
			$menu_link = ($menu_link != false) ?  $menu_link : $this->menu_array[$this->menu_name][$key]['menu_link'];			
		
			unset($this->auxilary[$this->menu_name][$key]);
			unset($this->menu_array[$this->menu_name][$key]);
			
			if(!$this->order) { $this->setOrder($key); }
			$this->setMenuItem($menu_item, $menu_link, $options);
		}
	}
	
	
	function unsetMenuItem($menu_item_code, $menu_name = false) {
		$menu_name = ($menu_name) ? $menu_name : $this->menu_name;
		$key = array_search($menu_item_code, $this->auxilary[$menu_name]);
		if($key !== false) {
			unset($this->auxilary[$menu_name][$key]);
			unset($this->menu_array[$menu_name][$key]);
		}
	}
	
	
	function setTemplate($value, $type = 'NORMAL') {
		$this->template = $value;
		$this->template_type = $type;
	}
	
	function setTemplateCustomRule($value = true) {
		$this->custom_rule = $value;
	}
	
	function setGetParams($get_params) {
		$this->get_params[] = $get_params;
	}
	
	
	function generate($menu_name = 'default') {
		
		if(!isset($this->menu_array[$menu_name])) { return; }
		ksort($this->menu_array[$menu_name]);
		
		$tpl = new tplTemplatez($this->template);
		
		// only if template with row/active and row/nonactive
		if($this->template_type == 'NORMAL') {
			$page_val = $this->_getCheckValue($_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
			$menu_key = $this->_getCurrentMenuItem($page_val, $menu_name);
			
			foreach($this->menu_array[$menu_name] as $k => $v){
				if($k == $menu_key){ 
					$tpl->tplSetNeeded('row/active'); 
				} else { 
					$tpl->tplSetNeeded('row/nonactive'); 
				}
				$tpl->tplParse(array_merge($this->options,$v),'row');
			}
		} else {
			foreach($this->menu_array[$menu_name] as $k => $v){
				$tpl->tplParse($v,'row');
			}
		}
		
		if($this->custom_rule) { $tpl->tplSetNeeded('/line'); }
		//else                   { $tpl->tplSetNeeded('/not_line'); }
		
		$tpl->tplParse();
		return $tpl->tplPrint(1);
	}

	
	function display($menu_name = 'default') {
		echo $this->generate($menu_name);
	}
	
	
	
	// get key of current menu
	function _getCurrentMenuItem($page_val, $menu_name) {
		
		
		if($this->default_value && !in_array($page_val, $this->auxilary[$menu_name])) {
			$menu_key = array_search($this->default_value, $this->auxilary[$menu_name]);
		} else {
			$menu_key = array_search($page_val, $this->auxilary[$menu_name]);
		}
		
		$menu_key = ($menu_key !== false) ? $menu_key : '654987654';
		return $menu_key;
	}
	
	
	function _getCheckValue($string) {
		
		if($this->equal_type == 'GET') {
			$get_str = (($pos = strpos($string, '?')) !== false) ? substr($string, $pos+1) : '';
			parse_str($get_str, $output);
			@$value = $output[$this->equal_value]; // 
		
		} elseif($this->equal_type == 'PAGE') {
		
			$value = substr($string, 0, strpos($string, '.')); // delete ext
			$value = (($pos = strrpos($value, '/')) !== false) ? substr($value, $pos+1) : $value; // delete before /
		
		} elseif($this->equal_type == 'DIR') {
			
			if(strpos($string, '/') === 0) {
				$string = substr($string, 1); // delete first /
			}
			
			// dirname(__FILE__);
			$string = substr($string, 0, strrpos($string, '/')); // delete after last
			
			$value = explode('/', $string);
			krsort($value);
			$value = implode('/', $value);
			$value = explode('/', $value);
			
			$equal = (!$this->equal_value) ? 0 : $this->equal_value - 1;
			$value = $value[$equal]; // 
		}
		
		return $value;
	}
}



class AppNavigation extends Navigation
{
	
	var $tbl_pref_custom;
	var $tbl_pref;
	var $tables = array('priv_module', 'priv_module_lang');
	var $page;
	var $msg = array();
	
	
	function AppNavigation() {
		
		$reg =& Registry::instance();
		$this->db 		=& $reg->getEntry('db');
		$this->tbl_pref =& $reg->getEntry('tbl_pref');
		//$this->priv     =& $reg->getEntry('priv');
		
		$this->tbl = (object) AppModel::_setTableNames($this->tables, 
										               $this->tbl_pref, 
										               $this->tbl_pref_custom);
													   
		$this->setPage($_SERVER['PHP_SELF']);
	}
	
	
	function setMenuMsg($msgs) {
		$this->msg = $msgs;
	}
	
	function setPage($val) {
		$this->page = $val;
	}
	
	function getSql($module_name) {
	
		//if($module_name == 'setting') {
			//$parent_id = 'p2.parent_setting_id';
			//$use_in_sub_menu_sub = 'NULL';			
			
		//} else {
			$parent_id = 'p2.parent_id';
			$use_in_sub_menu_sub = 'p2.use_in_sub_menu';
		//}

		$sql = "SELECT 
		p1.use_in_sub_menu AS use_in_sub_menu_top,
		p1.menu_name AS top_menu_name, 
		p1.module_name AS top_module_name,
		p2.by_default AS by_default,
		{$use_in_sub_menu_sub} AS use_in_sub_menu_sub, 
		p2.menu_name AS sub_menu_name,
		p2.module_name AS sub_module_name,
		p2.check_priv,
		p2.as_sub_menu
		
		FROM {$this->tbl->priv_module} p1, {$this->tbl->priv_module} p2 
		
		WHERE p1.id = {$parent_id}
		AND p1.module_name = '$module_name'
		AND p2.active = 1
		ORDER BY p2.sort_order";
		
		//echo "<pre>"; print_r($sql); echo "</pre>";
		return $sql;
	}
	
	
	// select from table priv_module
	function setMenu($module_name, $sub_menu_attrib = false) {
	
		$menu = false;
		
		$sql = $this->getSql($module_name);
		$result = mysql_query($sql) or die (db_error($sql));
		while($row = mysql_fetch_assoc($result)){
			$menu = true;
			
			// hide not authorized module, page, ...
			if(!isset($_SESSION['priv_']['all']) && $row['check_priv']) {
				if(!isset($_SESSION['priv_'][$row['sub_module_name']])) { continue; }
			}
						
			// miss top
			if($row['sub_module_name'] == 'all') { continue; }			
						
			$params = array();
			
			// generate different link go to page by default
			if($row['by_default']) {
				
				if(strpos($row['by_default'], '/')) {
					$param = explode('/', $row['by_default']);
					$i = 0;
					foreach($param as $k => $v) {
						$params[] = $this->sub_equal[$i++]['value'] . '=' . $v;
					}
					
				} else {
					$params = array($this->sub_equal[0]['value'] .'='. $row['by_default']);
				}
			
			// generate different link to go to sub page
			} elseif($row['use_in_sub_menu_sub'] == 'YES_DEFAULT') {
				$params = array($this->sub_equal[0]['value'] .'='. $row['sub_module_name']);
			}


			$params = implode('&', array_merge($this->get_params, $params)) . '&';
			
			// add menu to sub from top
			if($row['use_in_sub_menu_top'] != 'NO' && $row['use_in_sub_menu_top'] != ''  && !isset($use_in_sub_menu_top)) {
				$use_in_sub_menu_top = 1;
				$page = $this->page . '?' . $params . $this->equal_value . '=' . $row['top_module_name'];				
				
				if(isset($this->msg[$row['top_module_name']])) { $menu_name = $this->msg[$row['top_module_name']]; }
				else                                           { $menu_name = $row['top_menu_name']; }
				$this->setMenuItem($menu_name, $page);
			}
			
			
			$page = $this->page . '?' . $params . $this->equal_value . '=' . $row['sub_module_name'];
			
			if(isset($this->msg[$row['sub_module_name']])) { $menu_name = $this->msg[$row['sub_module_name']]; } 
			else                                           { $menu_name = $row['sub_menu_name']; }
			
			$this->setMenuItem($menu_name, $page);
			$page = '';
		}
		
		return $menu;
	}


	function generate($menu_name = 'default') {
		
		if(!isset($this->menu_array[$menu_name])) { 
			return $this->_generateEmpty();
		} else {
			return $this->_generateMenu($menu_name);
		}
	}
	
	
	function _generateMenu($menu_name) {
		
		ksort($this->menu_array[$menu_name]);
		
		$tpl = new tplTemplatez($this->template);
		
		// only if template with row/active and row/nonactive
		if($this->template_type == 'NORMAL') {
			$page_val = $this->_getCheckValue($_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
			$menu_key = $this->_getCurrentMenuItem($page_val, $menu_name);
			
			foreach($this->menu_array[$menu_name] as $k => $v){
				$v['menu_key'] = $this->auxilary[$menu_name][$k];
				if($k == $menu_key){ 
					$tpl->tplSetNeeded('row/active'); 
				} else { 
					$tpl->tplSetNeeded('row/nonactive'); 
				}
				$tpl->tplParse(array_merge($this->options,$v),'row');
			}
		} else {
			foreach($this->menu_array[$menu_name] as $k => $v){
				$tpl->tplParse($v,'row');
			}
		}
		
		//if($this->custom_rule) { $tpl->tplSetNeeded('/line'); }
		//else                   { $tpl->tplSetNeeded('/not_line'); }
		
		$tpl->tplParse();
		return $tpl->tplPrint(1);		
	}
	
	
	// just top line
	function _generateEmpty() {
		
		$tpl = new tplTemplatez(APP_TMPL_DIR . 'sub_menu_empty.html');		
		$tpl->tplParse();
		return $tpl->tplPrint(1);		
	}	

}



/*
$nav = new Navigation;

$nav->setEqualAttrib('GET', 'view');
$nav->setTemplate('../template/sub_menu1.html'); 

$nav->setDefault('history');

$nav->setMenuItem('Basic info', $_SERVER['PHP_SELF'].'?view=basic');
$nav->setMenuItem('History', $_SERVER['PHP_SELF'].'?view=history');
$nav->setMenuItem('Prescriptions', $_SERVER['PHP_SELF'].'?view=prescriptions');
$nav->setMenuItem('Account', $_SERVER['PHP_SELF'].'?view=account');

//$nav->setEqualAttrib('PAGE');
$nav->setMenuItem('Insurance', $_SERVER['PHP_SELF']);
$nav->setMenuItem('Recalls', $_SERVER['PHP_SELF'].'?view=recalls');
$nav->setMenuItem('Notes', $_SERVER['PHP_SELF'].'?view=notes');


$nav->display();
echo "<pre>"; print_r($nav); echo "</pre>";
*/


?>
